<template>
  <a-modal :open="open" :title="title" @ok="handleSubmit" @cancel="cancel" okText="确定" cancelText="取消">
    <a-form :model="menuForm" v-bind="layout" ref="menuFormRef">
      <a-row>
        <a-col :span="12">
          <a-form-item label="上级菜单" name="parentId" :rules="[{ required: true, message: '请选择上级菜单' }]">
            <a-tree-select v-model:value="menuForm.parentId"
              :field-names="{ label: 'label', value: 'id', options: 'children' }" style="width: 100%"
              placeholder="请选择上级菜单" :tree-data="parents" tree-default-expand-all
              @change="handleChange"></a-tree-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="类型" name="type" :rules="[{ required: true, message: '请选择类型' }]">
            <a-radio-group v-model:value="menuForm.type">
              <a-radio :value="1">菜单</a-radio>
              <a-radio :value="2">按钮</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
      
      <a-row>
        <a-col :span="12">
          <a-form-item label="菜单名称" name="label" :rules="[{ required: true, message: '请输入菜单名称' }]">
            <a-input v-model:value="menuForm.label" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="路由地址" name="path" :rules="[{ required: true, message: '请输入路由地址' }]">
            <a-input v-model:value="menuForm.path" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-item label="图标" name="icon">
            <a-select ref="select" v-model:value="menuForm.icon" style="width: 100%;">
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="组件名称" name="name" :rules="[{ required: true, message: '请输入组件名称' }]">
            <a-input v-model:value="menuForm.name" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-item label="组件地址" name="component" :rules="[{ required: true, message: '请输入组件地址' }]">
            <a-input v-model:value="menuForm.component" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="权限标识" name="code" :rules="getCodeRules">
            <a-input v-model:value="menuForm.code" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-item label="排序" name="sort" :rules="[{ required: true, message: '请输入排序值' }, { type: 'number', min: 1, max: 10000, message: '排序值范围为 1 - 10000' }]">
            <a-input-number id="inputNumber" v-model:value="menuForm.sort" :min="1" :max="10000" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script setup name="MenuModal">
import { ref, reactive, defineEmits, defineExpose, computed } from 'vue';
import { option, addMenu, updateMenu } from '@/api/menu';
import { message } from 'ant-design-vue';

// 定义弹框关闭 页面要刷新
const emit = defineEmits(['refresh']);

const layout = {
  labelCol: {
    span: 7,
  },
  wrapperCol: {
    span: 16,
  },
};

// 弹框的开关
const open = ref(false);
// 标题
const title = ref('新增');
const parents = ref([]);
// 表单对象
const menuForm = reactive({
  id: '',
  parentId: 0,
  label: "",
  name: '',
  icon: '',
  component: '',
  path: '',
  code: '',
  type: null,
  sort: null,
});
const roles = ref([]);
// 表单对象 用于清空表单数据
const menuFormRef = ref();
// 弹框类型 默认是新增
const type = ref(true);

// 获取上级菜单数据
const getParents = async () => {
  try {
    const optionRes = await option();
    parents.value = optionRes.data;
  } catch (error) {
    message.error('获取上级菜单数据失败');
  }
};

// 设置弹框的开闭 第一个参数是否是是新增  第二个参数是数据
const openModal = async (isNew = true, data) => {
  await getParents();
  open.value = true;

  if (data) {
    menuForm.parentId = data.id;
  }

  if (!isNew && data) {
    title.value = '编辑';
    type.value = false;
    for (const key in menuForm) {
      menuForm[key] = data[key];
    }
  } else {
    type.value = true;
    title.value = '新建';
  }
};

// 关闭弹框
const cancel = () => {
  open.value = false;
  menuFormRef.value.resetFields();
  console.log("关闭弹框");
};

// 提交表单
const handleSubmit = async () => {
  const valid = await menuFormRef.value.validate();
  if (!valid) {
    return;
  }

  try {
    if (type.value) {
      await addMenu(menuForm);
    } else {
      await updateMenu(menuForm);
    }
    cancel();
    emit('refresh');
    message.success('提交成功');
  } catch (error) {
    message.error('提交失败');
  }
};

const handleChange = (value) => {
  console.log(`selected ${value}`);
};

// 动态计算权限标识的验证规则
const getCodeRules = computed(() => {
  if (menuForm.type === 2) {
    return [{ required: true, message: '请输入权限标识' }];
  }
  return [];
});

// 在这里暴露这个方法 在外面调用
defineExpose({ openModal });
</script>

<style scoped>
.ant-form {
  margin-top: 36px;
}
</style>